package com.briup.client;

import com.briup.Configuration;
import com.briup.entity.Environment;
import com.briup.support.ConfigurationAware;
import com.briup.support.PropertiesAware;
import com.briup.util.Backup;
import com.briup.util.Log;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Collection;
import java.util.Properties;

/**
 * @Classname ClientImpl
 * @Description TODO
 * @Date 2023/11/20 19:40
 * @Created by 崔宗祺
 * @Version v1.0.0
 */

public class ClientImpl implements Client, PropertiesAware, ConfigurationAware {
    private String host;
    private int port;
    private Log log;
    private String filePath ;
    private Backup backup;
    @Override
    public void send(Collection<Environment> collection) throws Exception {
        Socket socket = new Socket(host, port);
        log.info("客户端创建成功 连接到服务器。。。。");
        Collection<Environment> coll = null;
        log.info("加载数据库备份文件");
        log.debug("备份文件路径" + filePath);
        coll = (Collection<Environment>) backup.load(filePath, Backup.LOAD_REMOVE);
        if (coll != null) {
            log.info("服务器数据正在备份");
            collection.addAll(coll);
        }
        try {
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(collection);
            oos.flush();
            oos.close();
            log.info("客户端发送数据完毕  即将关闭");
            socket.close();
        }catch (Exception e1){
            e1.printStackTrace();
            try {
                backup.store(filePath,collection, Backup.STORE_APPEND);
            }catch (Exception e2){
                e2.printStackTrace();
                log.info("备份失败");
            }
        }
    }

    @Override
    public void init(Properties properties) throws Exception {
        host = properties.getProperty("host");
        port = Integer.parseInt(properties.getProperty("port"));
        filePath = properties.getProperty("filePath");
    }

    @Override
    public void setConfiguration(Configuration configuration) throws Exception {
        log = configuration.getLogger();
        backup=configuration.getBackup();
    }
}

